
// var appId = '148368515196802'; // dev
var appId = '137754252688' // prod
var useYoutubeNewEmbed = false;
var videos = [];
var currentIndex;
var users = {};
var hasClickedAddCommentOnceBefo = false;
var hasPublishStreamPermission = false;

function onLoginStatus(response, fromLoginAttempt, forceDoLogin) {
 if (response.session) {
   if (response.perms) {
     var doLogin = forceDoLogin;
     if (!doLogin) {
       try {
         var perms = jQuery.parseJSON(response.perms);
         for (var i = 0; i < perms.extended.length; i++) {
           if (perms.extended[i] == 'read_stream') {
             doLogin = true;
           } else if (perms.extended[i] == 'publish_stream') {
             hasPublishStreamPermission = true;
           }
         }
       } catch(e) {
         console.log(e);
         // have to do this hackery bc when we accept the permission dialog in the case where we've authorized the app before, they just return response.perms = 'read_stream'
         doLogin = response.perms.indexOf('read_stream') != -1;
         if (doLogin) {
           onLoginStatus(response, false, true);
         }
         if (response.perms.indexOf('publish_stream') != -1) {
           hasPublishStreamPermission = true;
         }

       }       
     }      
     if (doLogin) {
       onLogin();
     } else {
       onLogout();
       showNeedPermissionMsg();
     }             
   } else {
     onLogout();
     showNeedPermissionMsg();
   }          
 } else {
   if (fromLoginAttempt) {
     showNeedPermissionMsg()
   } else {
     onLogout();
   }           
 }
}

function showNeedPermissionMsg() {
$('#logged-out-content').hide();
$('#need-permissions-content').show();
}

function logout() {
FB.logout(onLoginStatus);
}

function onLogout() {
  var foo = $('#fb-login-content');
  foo.html('<a href="javascript:login()">login</a>');          
  var iframe = document.getElementById('ze-iframe');
  if (iframe) {            
    document.getElementById('iframe-container').removeChild(iframe);
  }                    
  videos = [];
  users = {};
  window.removeEventListener('keyup', onKeyUp, false);
  $("#logged-in-content").hide();
  $("#logged-out-content").show();          
}

function login() {
FB.login(function(res) {
    onLoginStatus(res, true)
  }, {perms: 'read_stream'});
}

function onKeyUp(evt) {
	var keyCode = evt.keyCode;
	if (keyCode == 39) { // right arrow
		next();
	} else if (keyCode == 37) { // left arrow
		prev();
	} else if (keyCode == 32) { // space bar
		
	}
}


function onLogin() {
    // setup keyboard listeners
	window.addEventListener('keyup', onKeyUp, false);

    $("#logged-in-content").show();
    $("#logged-out-content").hide(); 
    $('#need-permissions-content').hide();                 
    var foo = $('#fb-login-content');
    foo.html('<a href="javascript:logout()">logout</a>');
    
    var postIdTerm = 'postId=';
    var postIdIndex = window.location.search.indexOf(postIdTerm);
    if (postIdIndex != -1) {
        var postId = window.location.search.substring(postIdTerm.length + 1);
        loadSpecificVideo(postId);
    } else {
        loadVideos();
    }
}

function loadSpecificVideo(postId) {
    $('#loading-content').show();  
    var query1 = 'SELECT created_time, attachment.media, message, actor_id, post_id, comments, likes FROM stream WHERE post_id = "' + postId + '"';
    console.log(query1);
    	FB.api({
    			    method: 'fql.multiquery',
    			    queries: {"query1" : query1, "query2":"SELECT id, name, url, pic FROM profile WHERE id IN (SELECT actor_id FROM #query1)"}
    			  }, onVideosLoaded);
}

function loadVideos(timestamp) {
    $('#loading-content').show();  
    var timeLimit = timestamp ? 'AND created_time < ' + timestamp : '';
    var query1 = 'SELECT created_time, attachment.media, message, actor_id, post_id, comments, likes FROM stream WHERE filter_key="nf" AND attachment.media != "" AND attribution != "Bandsintown" ' + timeLimit + ' limit 100';
    // console.log(query1);
    	FB.api({
    			    method: 'fql.multiquery',
    			    queries: {"query1" : query1, "query2":"SELECT id, name, url, pic FROM profile WHERE id IN (SELECT actor_id FROM #query1)"}
    			  }, onVideosLoaded);
}

function onVideosLoaded(response) {
    // set current index to videos array length because we assume we only call this method when we've reached the end
    currentIndex = videos.length;	

    // create a hash of user data
    $(response[1]['fql_result_set']).each(function(index, elem) {
      users[elem.id] = elem;
    });

    var resultPosts = response[0]['fql_result_set'];
    g_resultPosts = [];
    if (resultPosts.length) {
        // now get the video urls
        var atLeastOneVideoFound = false;
	    $(resultPosts).each(function(index, elem) {
	        if (parseInt(elem.comments.count) > 0) {
                g_resultPosts.push(elem);
            }
            if (elem.attachment.media.length > 0) {
                var attachment = elem.attachment.media[0];
                if (attachment.type == "video") {
                    var videoSourceUrl = attachment.video.source_url;
                    var videoParams = {url: videoSourceUrl, infoUrl: attachment.video.display_url, uid: elem['actor_id'], msg: elem.message, time: elem['created_time'], postId: elem.post_id, comments: elem.comments, likes: elem.likes};
                    if (videoSourceUrl.indexOf("youtube") != -1) {
                        videoParams.isYoutube = true;     
                        var displayUrl = attachment.video.display_url;                   
                        if (displayUrl.indexOf('youtu.be')) {
                            var arr = displayUrl.split("/");
                            videoParams.youtubeId = arr[arr.length - 1].split('&')[0];                          
                        } else {
                            videoParams.youtubeId = displayUrl.split("=")[1].split('&')[0];                          
                        }
                    }
	                videos.push(videoParams);
	                atLeastOneVideoFound = true;
	            }
            }
	    });
	    if (atLeastOneVideoFound) {
	        $('#controls').show();
	        $('#social-container').show();						    
            $('#loading-content').hide();						    
	        playVideo();
	    } else {
	        loadVideos(resultPosts[resultPosts.length - 1]['created_time']);
	    }
    } else {
        $('#loading-content').html("that's it for today folks. tune in again tmrw!");
        window.setTimeout(function() {
            $('#loading-content').hide();
        }, 5000);
    }    	  
}

function playVideo() {

    var iframe = document.getElementById('ze-iframe');
    if (!iframe) {
      iframe = document.createElement('iframe');
      iframe.setAttribute("style", "width: 700px; height: 422px;");
      iframe.setAttribute("id", "ze-iframe");          
      document.getElementById('iframe-container').appendChild(iframe);
    }
    var video = videos[currentIndex];
    var href = video.isYoutube && useYoutubeNewEmbed ? ('http://www.youtube.com/embed/' + video.youtubeId + '?autoplay=1') : video.url;
    var user = users[video.uid];
    $('#user-img').html('<a target="_blank" href="' + user.url  + '"><img src="' + user.pic + '"/></a>');        
    $('#user-name').html('<a target="_blank" href="' + user.url  + '">' + user.name + '</a>');                
    $('#user-comment').html(video.msg);
    renderPersonalizedLikeContainer();
    renderPersonalizedCommentsContainer();

    resetCommentsContainer();
    addLikeButton(video.infoUrl);
    addComments(video.infoUrl);
    iframe.src = href;
    $('#post-id').html(video.postId);
}

function resetCommentsContainer() {
    var commentsContainer = $('#comments-container');
    commentsContainer.hide();
    commentsContainer.css('visibility', 'hidden');
    hasClickedAddCommentOnceBefo = false;
}

function renderPersonalizedLikeContainer() {
    var video = videos[currentIndex];
    var total = video.likes.friends.length;
    if (total > 0) {
        FB.api(
          {
            method: 'users.getInfo',
            uids: video.likes.friends,
            fields: ['name']
          },
          function(response) {
              var str = '';
              $(response).each(function(index, elem) {
                  str += elem.name;
                  if (index != total - 1) {
                      str += ', '
                  }
              });
              str += ' like' + (total == 1 ? 's ' : ' ') + 'this';  
              $('#personalized-like-container').html(str);            
          }
        );
    } else {
        $('#personalized-like-container').html('');            
    }
}

function renderPersonalizedCommentsContainer() {
    var video = videos[currentIndex];
    var total = video.comments.comment_list.length;
    if (total > 0) {
        FB.api({
            method: 'fql.query',
            query: 'select text, fromid from comment where post_id = "' + video.postId + '" limit 10'
        }, function(res) {
            // get fbIds
            var fbIds = [];
            var comments = res;
            $(comments).each(function(index, elem) {
                fbIds.push(elem.fromid);
            });
            FB.api(
                {
                    method: 'users.getInfo',
                    uids: fbIds,
                    fields: ['name, uid, profile_url']
                },
                function(response) {
                    // create a map of uid to name
                    var map = {};
                    $(response).each(function(index, elem) {
                        map[elem.uid] = {name: elem.name, profile_url: elem.profile_url};
                    });
                                        
                    var str = '';
                    $(comments).each(function(index, elem) {
                        var obj = map[elem.fromid];
                        str += '<div class="comment"><a target="_blank" href="' + obj.profile_url + '">' + obj.name + '</a>: "' + elem.text + '"</div>' ;
                    });
                    $('#personalized-comments-container').html(str);            
                });
        });
        
        
       
    } else {
        $('#personalized-comments-container').html('');            
    }
}

function addLikeButton(videoInfoUrl) {  
FB.Event.unsubscribe('edge.create', onLike);    
FB.Event.unsubscribe('edge.remove', onUnlike);              
var likeContainer = document.getElementById('like-container');        
var fbLike = document.getElementById('ze-fb-like');
if (fbLike) {
  likeContainer.removeChild(fbLike);
}
fbLike = document.createElement('fb:like');
fbLike.setAttribute("layout", "button_count");
fbLike.setAttribute("width", "90");
fbLike.setAttribute("width", "21");          
fbLike.setAttribute("font", "arial");   
fbLike.setAttribute('style', "width:90px; height:21px;");                 
fbLike.setAttribute("colorscheme", "dark");          
fbLike.setAttribute("id", 'ze-fb-like');
likeContainer.appendChild(fbLike);
fbLike.setAttribute("href", videoInfoUrl);
fbLike.setAttribute("send", "true");          
FB.XFBML.parse(likeContainer);

FB.Event.subscribe('edge.create', onLike);    
FB.Event.subscribe('edge.remove', onUnlike);              
}

function onLike(res) {        
// res is url that was liked
if (!hasPublishStreamPermission) {
  if (!confirm('you just liked the video! would you also like to like your friend\'s event?')) {
    return;
  }
  getPublishStreamPermission(doLike)
} else {
  doLike();
}
}

function doLike() {
var video = videos[currentIndex];
FB.api('/' + video.postId + '/likes', 'post', null, function(response) {
  if (!response || response.error) {
    alert('Error liking this post');
  } else {
    console.log('success liking this post');
  }
});
}

function onUnlike(res) {
if (!hasPublishStreamPermission) {
  getPublishStreamPermission(doUnlike)
} else {
  doUnlike();
}
}

function doUnlike() {
var video = videos[currentIndex];
FB.api('/' + video.postId + '/likes', 'delete', null, function(response) {
  if (!response || response.error) {
    alert('Error unliking this post');
  } else {
    console.log('success unliking this post');
  }
});
}

function getPublishStreamPermission(onSuccess) {
FB.ui({
    method: 'permissions.request',
    perms: 'publish_stream'
  },
  function(response) {
    // example response: {perms: "publish_stream", session: {...}, status: "connected"}
    if (response.perms && response.perms.indexOf('publish_stream') != -1) {
      hasPublishStreamPermission = true;
      onSuccess();
    }            
  });
}

function openExampleFBDialog() {
FB.ui(
   {
     method: 'feed',
     name: 'Facebook Dialogs',
     link: 'http://developers.facebook.com/docs/reference/dialogs/',
     picture: 'http://fbrell.com/f8.jpg',
     caption: 'Reference Documentation',
     description: 'Dialogs provide a simple, consistent interface for applications to interface with users.',
     message: 'Facebook Dialogs are easy!'
   },
   function(response) {
     if (response && response.post_id) {
       alert('Post was published.');
     } else {
       alert('Post was not published.');
     }
   }
 );
}

function addComments(videoInfoUrl) {
FB.Event.unsubscribe('comment.create', onAddComment);
var commentsContainer = document.getElementById('comments-container');        
var fbComments = document.getElementById('ze-fb-comments');
if (fbComments) {
  commentsContainer.removeChild(fbComments);
}
fbComments = document.createElement('fb:comments');
fbComments.setAttribute('num_posts', '3');
fbComments.setAttribute('width', '500');        
fbComments.setAttribute('id', 'ze-fb-comments');
fbComments.setAttribute('style', 'background-color: #fff; border: 10px solid #777');
commentsContainer.appendChild(fbComments);
fbComments.setAttribute('href', videoInfoUrl);                
FB.XFBML.parse(commentsContainer);
FB.Event.subscribe('comment.create', onAddComment);

}



function onAddComment(res) {        
// example res: {commentID: "10150099590063176", href: "http://www.youtube.com/watch?v=kL33YdWhPLw", parentCommentID: undefined}
if (!hasPublishStreamPermission) {
  if (!confirm('thx for commenting on the video! would you also like to post the comment on your friend\'s event?')) {
    return;
  }
  getPublishStreamPermission(function() {
      doAddComment(res.href)
    });
} else {
  doAddComment(res.href);
}
}

function doAddComment(url) {
FB.api(
  {
    method: 'fql.query',
    query: 'select text from comment where object_id in (select comments_fbid from link_stat where url="' + url + '") order by time desc limit 1'
  },
  function(res) {
    var video = videos[currentIndex];
    FB.api('/' + video.postId + '/comments', 'post', {message: res[0].text}, function(response) {
      if (!response || response.error) {
        alert('Error adding comment to friend\'s post');
      } else {
        console.log('success adding comment to friend\'s post');
      }
    });
  }
);
}



function prev() {
if (currentIndex > 0) {
  currentIndex--;
  playVideo();          
}
}

function next() {
if (currentIndex < videos.length - 1) {
  currentIndex++;
  playVideo();
} else {
  loadVideos(videos[videos.length - 1].time);
}
}      
function addComment() {
var commentsContainer = $('#comments-container');
if (commentsContainer.css('display') == 'none') {
  commentsContainer.show();
}        
if (commentsContainer.css('visibility') == 'hidden') {
  commentsContainer.css('visibility', 'visible');
} else {
  commentsContainer.css('visibility', 'hidden');          
}
if (!hasClickedAddCommentOnceBefo) {
  hasClickedAddCommentOnceBefo = true;
  document.body.scrollTop = document.body.scrollTop + 300;
}        
}


